/**
 * @class 层级，用于生成各个层级放置于舞台上
 * @example 顺序为 地图层 人物层 效果层 对话层 按钮/UI层
 */
class Layer {
    /**
     * @constructor
     */
    constructor(name) {
        this.name = name;
        this._gen = {}; // 层级对象
        this._sequence = []; // 发生序列
        this.map = null; // 地图层
        this.character = null; // 人物层
        this.effect = null; // 效果层
        this.talk = null; // 对话层
        this.ui = null; // 按钮/UI层
    }

    /**
     * 添加层级
     * @param {String} name - 层级名字
     * @param {Number} w - 宽
     * @param {Number} h - 高
     */
    addLayer(name, w, h) {
        this[name] = {
            canvas: document.createElement('canvas'),
        }
        this[name].canvas.id = name;
        this[name].canvas.width = w;
        this[name].canvas.height = h;
        this[name].ctx = this[name].canvas.getContext('2d');
        return this;
    }

    /**
     * 添加绘制对象-以按照顺序绘制
     * @param {String} name 名字
     * @param {Number}  index 层级/绘制顺序
     * @param {Function} cb 包含绘制方法的函数
     */
    add(name, index, cb) {
        this._gen[name] = { index, [cb.name]: cb };
        this._sequence = [];
        let keys = Object.keys(this._gen);
        for (let i = 0; i < keys.length; i++) {
            let name = keys[i];
            let cb = this._gen[name][Object.keys(this._gen[name])[1]];
            this._sequence.splice(this._gen[name]['index'], 0, cb);
        }
        return this;
    }

    /**
     * 执行层级绘制
     */
    run() {
        let self = this;
        let gen = function* () {
            for (let i = 0; i < self._sequence.length; i++) {
                yield self._sequence[i];
            }
        }
        let g = gen();
        let next = () => {
            let res = g.next();
            if(res.done) {
                return;
            }
            res.value();
            next();
        }
        next();
    }
}

module.exports = Layer;